﻿using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Net;
using System.Windows;
using System.Windows.Controls;
//using System.Windows.Documents;
//using System.Windows.Input;
//using System.Windows.Media;
//using System.Windows.Media.Animation;
//using System.Windows.Shapes;
using System.Windows.Controls.Primitives;

namespace uhul.Controls
{


  /// <summary>
  /// templated control, enhances normal Button by 2 more TemplateVisualStates (Busy, Free)
  /// to let button drawing signalize some busy animation to user
  /// </summary>
  [TemplateVisualState(Name = "Busy", GroupName = "BusyStates")]
  [TemplateVisualState(Name = "Free", GroupName = "BusyStates")]
  public class BusyButton : Button
  {

    //public event RoutedEventHandler Busy;
    //public event RoutedEventHandler Free;

    int _isBusy;

    public BusyButton()
    {
      this.DefaultStyleKey = typeof(BusyButton);
      _isBusy = 0; //reset busy indicator
    }



    

    public static readonly DependencyProperty IsBusyProperty =
      DependencyProperty.Register("IsBusy", typeof(bool),
      typeof(BusyButton), new PropertyMetadata(false, new PropertyChangedCallback(onIsBusyChanged)));

    /// <summary>
    /// get/set busy indicator for AppButton
    /// </summary>
    public bool IsBusy
    {
      get { return (bool)GetValue(IsBusyProperty); }
      set
      {
        if (value)
          _isBusy++;

        else if (_isBusy > 0)
          _isBusy--;

        if (_isBusy == 0 || (_isBusy == 1 && value))
          SetValue(IsBusyProperty, value);

        //if (value == true)
        //{
        //  if (Busy != null)
        //    Busy.Invoke(this, new RoutedEventArgs());
        //}
        //else
        //{
        //  if (Free != null)
        //    Free.Invoke(this, new RoutedEventArgs());
        //}


      }
    }



    private static void onIsBusyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
      bool newVal = (bool)e.NewValue;
      if (newVal)
        VisualStateManager.GoToState((Control)d, "Busy", true);
      else
        VisualStateManager.GoToState((Control)d, "Free", true);

    }


  }

}
